package DailyQuestion;

//在判断函数外执行count++，避免重复
public class 甲板上的战舰_419 {
    static boolean[][] isVis;
    static int[] dx = {0, 0, 1, -1};
    static int[] dy = {1, -1, 0, 0};
    int n, m, count;
    public int countBattleships(char[][] board) {
        n = board.length;
        m = board[0].length;

        isVis = new boolean[n][m];
        count = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (board[i][j] == 'X' && !isVis[i][j]) {
                    count++;
                    find(i, j, board);
                }
            }
        }
        return count;
    }

    private void find(int i, int j, char[][] board) {
        for (int k = 0; k < 4; k++) {
            int x = i + dx[k], y = j + dy[k];
            if (x >= 0 && x < n && y >= 0 && y < m
                    && !isVis[x][y] && board[x][y] == 'X') {
                isVis[x][y] = true;
                find(x, y, board);
            }
        }
    }
}
